<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_M_MATRIX.php' );
require_once( '../system/mdao/Class_M_MAP_GROUP.php' );
require_once( '../system/mdao/Class_M_MAP_GROUP_WEEK.php' );
require_once( '../system/mdao/Class_M_MAP_GROUP_SHOP.php' );
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );
require_once( '../system/aoki_m_plus.php' );

Class_PWD::valid_auth(AOKI_AUTH_MAP_GROUP, $login['staff_auth']);
$isG7  = FALSE;
if   ($login['staff_auth'] == 'G-7') {
	$isG7 = TRUE;
}

$dao  = new Class_M_MAP_GROUP_SHOP;

if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if( isset($_GET['ww']) && $_GET['ww'] != '' ){
		$matrix_cd   = $_GET['ww'];
		$map_no      = $_GET['mm'];
		$where[]     = "a.matrix_cd = '{$matrix_cd}'";
		$where[]     = "a.map_no    = '{$map_no}'";
		
		$formdata["matrix_cd"] = $matrix_cd;
		$formdata["map_no"]     = $map_no;
		
		$data  = $dao->search( $where );
		$formdata["d"] = $data;
		
		/*
		$dao_mg  = new Class_M_MAP_GROUP;
		$data_mg = $dao_mg->get( $map_no );
		*/
		$data_mg = $dao->getMapShopHead( $matrix_cd, $map_no );
		
		$formdata["sort"]       = $aoki_map_sort[$data_mg["sort"]];
		$formdata["media_name"] = $data_mg["media_name"];
		
		$formdata["year4"]      = $data_mg["year4"];
		$formdata["week_seq"]   = $data_mg["week_seq"];
		$formdata["week_cd"]    = $data_mg["week_cd"];
		$formdata["u_time"]     = $data_mg["u_time"];
		
	}else{
		//$forms['auth'] = 0;
		echo "パラメタエラー";
		exit;
	}
}else{
	$forms = $_POST;
	$matrix_cd   = $forms["matrix_cd"];
	
	if( $forms['mode'] == 'input' ||  $forms['mode'] == 'sort'  ){
		//フォームデータ整形
		$values  = array();
		$vidarr  = array();
		$err     = new Class_ERROR("","");
		$chk     = $dao->get_checks();
		$maxlens = $dao->get_maxlens();
		
		/*
		array_multisort($volume, SORT_ASC, $values);
		foreach ($forms["shop_cd"] as $k => $v ) {
		}
		*/
		
		foreach ($forms["shop_cd"] as $k => $v ) {
			$vidarr[$k] = $forms["id"][$k] ;
			$values[$k]["matrix_cd"]      = $forms["matrix_cd"];
			$values[$k]["map_no"]         = $forms["map_no"];
			$values[$k]["seq"]            = $forms["seq"][$k] ;
			$values[$k]["shop_cd"]        = $forms["shop_cd"][$k] ;
			$values[$k]["group_no"]       = $forms["group_no"][$k] ;
			$values[$k]["mark"]           = $forms["mark"][$k]== '1'   ? '1' : (empty($forms["congruent_ins"][$k]) ? '0' : '9')   ;
			$values[$k]["comm"]           = $forms["comm"][$k] ;
			$values[$k]["congruent_map"]  = $forms["congruent_map"][$k] ;
			$values[$k]["congruent_ins"]  = $forms["congruent_ins"][$k] ;
			$values[$k]["ins_load_ratio"] = empty($forms["ins_load_ratio"][$k]) ? 0 : $forms["ins_load_ratio"][$k];
			$values[$k]["memo"]           = $forms["memo"][$k] ;
			$values[$k]["dummy"]          = $forms["dummy"][$k] =='1' ? '1' : '0' ;
			//echo "*".$values[$k]["shop_cd"]."*".$forms["dummy"][$k] ."*--";
			
			$values[$k]["service"]        = $forms["service"][$k] ;
			
			$volume[$k] = $forms["seq"][$k] ;
		}
		
	if( $forms['mode'] == 'input' ){
	
				//削除.更新のデータ作成
				$where = array();
				
				$where[]     = "a.matrix_cd = '".$forms["matrix_cd"]."'";
				$where[]     = "a.map_no    = '".$forms["map_no"]."'";
				$dbarray     = $dao->search( $where );
				$datadel = array();
				foreach($dbarray as $k=>$v) {
					$delflg = TRUE;
					
					foreach($values as $kk=>$vv) {
						if ($v["shop_cd"] == $vv["shop_cd"] ) {
							$delflg = FALSE;
							break;
						}
					}
					if ($delflg){
						$datadel[]  = $v["id"];
					} else {
						$dataedit[] = $v["id"];
					}
				}
				
				$err_flg = false;
				$cont_ins_arr = array();
				
				
				foreach ($values as $k => $v ) {
					$shop_cd = $v['shop_cd'];
					foreach ($chk as $kcol => $chkval) {
						$err_mes[$kcol]  = $err->check( $v[$kcol], $chkval );
						if (!( $err->clear )) {
							$err_flg  = true;
							break;
						}
					}
					
					if ($err_flg) {
						break;
					}
					
					foreach ( $maxlens as $kk => $vv ) {
						$err_mes[$kk] =$err->check_size($v[$kk], $vv);
						if (!( $err->clear )) {
							$err_flg  = true;
							break;
						}
					}
					
					if ( !empty($v["congruent_ins"]) ) {
						if (empty($v["group_no"])) {
							$err_mes["group_no"]  = $err->format_msg("店舗「{$shop_cd}」の合同折込を入力される場合, 入力必須です" );
						}else {
							$group_no = $v["group_no"];
							if ( $cont_ins_arr[$group_no]) {
								$is_same_ins = true;
								foreach ($cont_ins_arr[$group_no] as $gk =>$gv) {
									if ($gv["congruent_ins"] != $v["congruent_ins"]) {
										$is_same_ins = false;
									}
								}
								if  (!$is_same_ins ) {
									
									$err_mes["group_no"]  = $err->format_msg("同じグループNO「{$group_no}」の合同折込の値は違います" );
								}else{
									$cont_ins_arr[$group_no][$shop_cd]["congruent_ins"] =  $v["congruent_ins"] ;
									$cont_ins_arr[$group_no][$shop_cd]["mark"] =  $v["mark"] ;
								}
							}  else {
								$cont_ins_arr[$group_no][$shop_cd]["congruent_ins"] =  $v["congruent_ins"] ;
								$cont_ins_arr[$group_no][$shop_cd]["mark"] =  $v["mark"] ;

							}
						}
						if (empty($v["ins_load_ratio"])) {
							//$err_mes["ins_load_ratio"]  = $err->format_msg("店舗「{$shop_cd}」の合同折込を入力される場合, 入力必須です" );
							$values[$k]["ins_load_ratio"] = 0;
						}
					}
					
					
					if ($err_flg) {
						break;
					}
					
				}
				
				if( $err->clear ){
					//print_r($cont_ins_arr);
					foreach ( $cont_ins_arr as $kk => $vv ) {
						$count_all = 0;
						$count_parent = 0;
						$group_no = $kk;
						foreach ( $vv as $key => $val ) {
							$congruent_ins = $val["congruent_ins"];
							$count_all ++;
							if ($val["mark"] == '1') {
							//if (!empty($val["mark"])) {
								$count_parent++;
							}
						}
						if ($count_parent != 1) {
							$err_mes["mark"]  = $err->format_msg("グループNO「{$group_no}」の親店舗はひとつを指定してください{$count_parent}" );
						}
						$count_G = substr(trim($val["congruent_ins"]),0,1) * 1 ;
						if ($count_all != $count_G ) {
							$err_mes["group_no"]  = $err->format_msg("グループNO「{$group_no}」の店舗数({$count_all})と合同折込数({$count_G})は違います" );
						}
					}
				}
				if( $err->clear ){
					try {
						$dao->begin_trans();
						$executeflg = TRUE;
						$dao_wk = new Class_M_MAP_GROUP_WEEK($dao->get_db());
						$wk_values["map_no"] = $forms['map_no'];
						$dao_wk->editbywhere(" map_no = {$forms['map_no']} and  matrix_cd = {$forms['matrix_cd']}", $wk_values);
						
						foreach ($datadel as $k=>$v) {
							if ($dao->remove($v)) {
							} else {
								$executeflg = FALSE;
							}
						}
						foreach ($values as $k => $v ) {
							if( $vidarr[$k] == '' ){
								if ($id = $dao->add($v)) {
									//$values[$k]['id'] = $id;
								} else {
									$executeflg = FALSE;
									break;
								}
							}else{
								if ($dao->edit( $vidarr[$k], $v )) {
								} else {
									$executeflg = FALSE;
									break;
								}
							}
						}
						
						if  ($executeflg) {
							$dao->commit_trans();
							//$smarty->assign('message', '保存が完了しました。');
							$sqlmessage = "保存が完了しました。";
						} else {
							$dao->rollback_trans();
							//$smarty->assign('message', '保存が失敗しました。');
							$sqlmessage = "保存が失敗しました。";
						}
					} catch (Exception $e) {
						$dao->rollback_trans();
						$sqlmessage = "ＤＢエラーで失敗しました。";
					}
					$phase = 'complete';
				}else{
					$phase = 'input';
				}
			}
		}
		$formdata["map_no"]     = $forms["map_no"];
		$formdata["matrix_cd"]  = $forms["matrix_cd"];
	}



if (  (isset($err) && (!( $err->clear ))) || ($forms['mode'] == 'sort')  ) {
	$errfields = $dao->get_errorfields();
	$errmsg = "";

	foreach ($err_mes as $k=>$v) {
		if (!empty($v)) {
			$errmsg =$errmsg.$errfields[$k]." : ".$v;
			break;
		}
	}
	$formdata["sort"]       = $forms["sort"];
	$formdata["media_name"] = $forms["media_name"];
	$formdata["year4"]      = $forms["year4"];
	$formdata["week_seq"]   = $forms["week_seq"];
	$formdata["week_cd"]    = $forms["week_cd"];
	$formdata["u_time"]     = $forms["u_time"];
	foreach ($values as $k => $v ) {
		$values[$k]["id"]           = $forms["id"][$k];
		$values[$k]["shop_name"]    = $forms["shop_name"][$k];
		//$values[$k]["smx"]     = $forms["shop_smx"][$k];
	}
	if( $forms['mode'] == 'sort' ){
		$phase = 'input';
		foreach ($values as $key => $row) {
			$seqs[$key] = $row['seq'];
		} 
	}
	array_multisort($seqs, SORT_ASC, $values); 
	
	
	$formdata["d"]       =  $values;
	
} else {
	//$formdata[$group_index]["h"]["errmsg"]     = $sqlmessage;
}

$smarty->assign('isG7', $isG7 );
if( isset( $formdata ) ) $smarty->assign('forms',  $formdata);
if( isset( $err_mes ) )  $smarty->assign('errmsg',    $errmsg);
$smarty->assign('message', $sqlmessage);
$smarty->assign('congruent',      $aoki_congruent );
$smarty->assign('congruent_ins', $aoki_congruent_ins );
$smarty->assign('phase',  $phase );
$smarty->assign('menu',   $smarty->fetch('menu.html') );
$smarty->assign('logout', $smarty->fetch('logout.html') );
$smarty->assign('footer', $smarty->fetch('footer.html') );

$smarty->display('mmapshop_form.html');
?>